import './index.scss';
import React, { useRef } from 'react';
import { formatDateTime } from '../../../libs/utils';
import Modal from '../index';

function EditModal(props) {
  //submitEdit是一个父组件传下来的方法
  const { isShowEditModal, data, submitEdit } = props;
  const inputRef = useRef();
  const checkRef = useRef();

  //点击编辑事件模态框里面的确定按钮触发提交更改编辑表单内容
  const formatNewData = () => {
    const val = inputRef.current.value.trim();
    const valLen = val.length;

    if (valLen === 0) {
      //放入原本value内容
      inputRef.current.value = data.content;
      return;
    }

    //编辑为新的内容
    const newData = {
      id: new Date().getTime(),
      //更新新编辑的内容
      content: val,
      //获取当前checked状态
      completed:checkRef.current.checked
    }

    //submitEdit(新的数据对象，原来的时间戳)
    submitEdit(newData, data.id);
  }

  return (
    // <Modal>children</Modal>
    <Modal
      isShowModal={isShowEditModal}
      modalTitle="编辑事件"
    >
      <p className="topic">时间: { formatDateTime(data.id) }</p>
      <p className="topic">
        <textarea
          className='text-area'
          ref={inputRef}
          defaultValue={data.content}
        ></textarea>
      </p>
      <p className="topic">状态：
        <input
          type="checkbox"
          defaultChecked={data.completed ? true : false}
          ref={checkRef}
        />
      </p>
      <button
        className='btn btn-primary confirm-btn'
        onClick={formatNewData}
      >确定</button>
    </Modal>
  );
}

export default EditModal;